import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;


public class HttpClientUtil {
	
    public static String doPost(Map<String, String[]> params, String gateway) {
		try {

			HttpClient client = new HttpClient();
			client.getParams().setContentCharset("utf-8");
			PostMethod post = new PostMethod(gateway);
			Set<String> keyset = params.keySet();
			for(Iterator<String> it = keyset.iterator(); it.hasNext(); ){
				String key = (String)it.next();
				String[] valueArr = params.get(key);
				for(int i=0; i<valueArr.length; i++) {
					NameValuePair param = new NameValuePair(key, URLDecoder.decode(valueArr[i],"utf-8"));
					System.out.println("-------------------------->params["+key+"]:"+URLDecoder.decode(valueArr[i],"utf-8"));
					post.addParameter(param);
				}
			}
			client.executeMethod(post);

			Reader r = new InputStreamReader(post.getResponseBodyAsStream(), "utf-8");
			return IOUtils.toString(r);
		} catch (Exception ex) {	
			ex.printStackTrace();
		}
		return "";
    }
    
    public static String doGet(Map<String, String[]> params, String gateway) {
		try {

			HttpClient client = new HttpClient();
			client.getParams().setContentCharset("utf-8");
			Set<String> keyset = params.keySet();
			int index = 0;
			for(Iterator<String> it = keyset.iterator(); it.hasNext(); ){
				String key = (String)it.next();
				String[] valueArr = params.get(key);
				for(int i=0; i<valueArr.length; i++) {
					if(index!=0){
						gateway += "&" + key + "=" + valueArr[i];
					} else {
						gateway += "?" + key + "=" + valueArr[i];
					}
					index++;
				}
			}
			System.out.println("-------------------------->gateway:"+URLDecoder.decode(gateway,"utf-8"));
			GetMethod get = new GetMethod(gateway);
			client.executeMethod(get);
			Reader r = new InputStreamReader(get.getResponseBodyAsStream(), "utf-8");
			return IOUtils.toString(r);
		} catch (Exception ex) {	
			ex.printStackTrace();
		}
		return "";
    }
}
